package models

import (
	"golanger.com/utils"
	"jk/jklog"
	// "labix.org/v2/mgo"
)

const (
	shidbname = "db"
)

// ShiCi main content
// The name and title make the unique
type JKShiCiContentItem struct {
	Name       string // the name of shici
	Title      string // subtitle
	Author     string // who write this shici
	RecordTime int64  // the time set shici to this page
	CreateTime int64  // the time which shici writen
	Content    string // the main content of this shici
}

type JKShiCiContents struct {
}

var (
	JKShiCiCol = utils.M{
		"name": "shici",
	}
)

func NewJKShiCi() *JKShiCiContents {
	return &JKShiCiContents{}
}

func (sc *JKShiCiContents) JKGetshicis(query interface{}, m interface{}) error {
	if err := JKGetCollection(shidbname, JKShiCiCol).Find(query).Sort("-RecordTime").All(m); err != nil {
		jklog.L().Errorln("Get Items Error")
		return err
	}
	return nil
}

func (sc *JKShiCiContents) JKshiciInsert(item interface{}) error {
	if err := JKGetCollection(shidbname, JKShiCiCol).Insert(item); err != nil {
		return err
	}
	return nil
}
func (sc *JKShiCiContents) JKshiciUpdate(item interface{}, update interface{}) error {
	change := utils.M{
		"$set": update,
	}
	return JKGetCollection(shidbname, JKShiCiCol).Update(item, change)
}

func (sc *JKShiCiContents) JKshiciRemove(item interface{}) error {
	if err := JKGetCollection(shidbname, JKShiCiCol).Remove(item); err != nil {
		return err
	}
	return nil
}

func (sc *JKShiCiContents) JKshiciCounts() int {
	n, _ := JKGetCollection(shidbname, JKShiCiCol).Find(nil).Count()
	return n
}

func (sc *JKShiCiContents) JKshiciExist(query interface{}) bool {
	n, err := JKGetCollection(shidbname, JKShiCiCol).Find(query).Count()
	if err != nil {
		jklog.L().Errorln("query fail ", err)
		return true
	}
	if n == 0 {
		return false
	} else {
		return true
	}
}

func (sc *JKShiCiContents) JKshiciQuery(query interface{}, save interface{}) error {
	if err := JKGetCollection(shidbname, JKShiCiCol).Find(query).One(save); err != nil {
		return err
	}
	return nil
}
